import { type IRouterParams } from "../interface"
import { ReflectUtil } from "../di"
import { buildMethodKey } from "../common"

export function Router(params: IRouterParams) {
  return function (target, targetKey: string, descriptor: PropertyDescriptor) {
    /**
     * 将一个 clazz A 上所有的 @Router 合并
     * @Get('/x') function fa(){}
     * @Post('/y') function fb(){}
     * props = {
     *   'A_fa' : {prototype: A, methodName:'fa', method: 'GET', path: '/x'},
     *   'A_fb' : {prototype: A, methodName:'fb', method: 'POST', path: '/y'}
     * }
     */
    const routerKey = buildMethodKey(target, targetKey)
    // console.log(`@Router routerKey = ${routerKey}, target = ${getClassName(target)}, method = ${targetKey}`)
    const scannedRouters = ReflectUtil.getRouters(target) || []
    if(scannedRouters[routerKey]){
      throw new Error(`@Router ${routerKey} 重复了.`)
    }
    const props = {
      ...scannedRouters,
      [routerKey]: {
        prototype: target,
        methodName: targetKey,
        handle: target[targetKey],
        ...params
      }
    }
    ReflectUtil.defineRouter(target, props)
  }
}

export const Get = (path: string): Function => {
  return Router({ method: "GET", path })
}

export const Post = (path: string): Function => {
  return Router({ method: "POST", path })
}

export const Put = (path: string): Function => {
  return Router({ method: "PUT", path })
}

export const Delete = (path: string): Function => {
  return Router({ method: "DELETE", path })
}
